import json
import uuid
import time
from datetime import datetime
from typing import List


class Prompt:
    def __init__(self,role:str,content:str,parent_id:str = None,metadata : dict = None):
        self.id = uuid.uuid4().hex
        self.role = role
        self.content = content
        self.parent_id = parent_id
        self.metadata = metadata or {}
        self.timestamp = datetime.utcnow().isoformat()

    def to_dict(self):
        """将prompt对象转为字段对象（便于序列化）"""
        return {
            "id": self.id,
            "role": self.role,
            "content": self.content,
            "parent_id": self.parent_id,
            "metadata": self.metadata,
            "timestamp": self.timestamp
        }


#定义上下文链
class ContextChain:
    def __init__(self):
        self.prompts = {}

    def add_prompt(self,prompt:Prompt):
        self.prompts[prompt.id] = prompt

    def get_chain(self,end_id:str) -> list:
        """
        追溯指定end id对应的prompt，回溯父prompt，构建完整上下文链
        :param end_id:
        :return:
        """
        chain = []
        current = self.prompts.get(end_id)
        while current:
            chain.insert(0,current)
            if current.parent_id:
                current = self.prompts.get(current.parent_id)
            else:
                break
        return chain

    def print_chain(self,end_id:str):
        chain = self.get_chain(end_id)
        print("当前上下文====")
        for prompt in chain:
            print(f"[{prompt.id}.role] {prompt.content} {prompt.timestamp}")

    def get_prompt_chain(self, end_id: str) -> List[Prompt]:
        """
        根据 end_id 向前追溯上下文链，返回从根到当前节点的Prompt列表。
        """
        chain = []
        current = self.prompts.get(end_id)
        while current:
            chain.insert(0, current)
            if current.parent_id:
                current = self.prompts.get(current.parent_id)
            else:
                break
        return chain
    def print_context(self, end_id: str):
        chain = self.get_prompt_chain(end_id)
        print("=== 上下文链 ===")
        for p in chain:
            print(f"[{p.role}] {p.content} ({p.id[:6]})")


class Task:
    def __init__(self,task_name:str,description:str,parent_task=None):
        self.task_id = uuid.uuid4().hex
        self.task_name = task_name
        self.description = description
        self.parent_task = parent_task
        self.subtasks = []
        self.context_chain = ContextChain()

    def add_subtask(self,subtask):
        self.subtasks.append(subtask)

    def add_prompt(self,prompt:Prompt):
        self.context_chain.add_prompt(prompt)


    def preserve_semantics(chain:ContextChain,current_prompt:Prompt) -> str:
        """
        合并当前prompt对应的上下文链中的所有内容，保持语义连续
        :param current_prompt:
        :return:
        """
        prompts  = chain.get_chain(current_prompt.id)
        merge_text = "\n".join([p.content for p in prompts])
        return merge_text


if __name__ == '__main__':
    #创建主任务
    main_task = Task("建立筛选","评估候选人是否符合岗位要求，根据简历及历史对话判断综合匹配度")
    #添加系统初始化prompt作为任务上下文链的根节点
    system_prompt = Prompt(
        role="system",
        content="启动候选人评估任务，确定岗位要求为：熟悉python，经验丰富的后端开发"
    )
    main_task.add_prompt(system_prompt)

    #子任务:解析建立内容
    subtask_parse = Task("解析简历","提取候选人简历中的基本信息：如：教育背景，工作经验和技能")
    main_task.add_subtask(subtask_parse)

    resume_prompt = Prompt(
        role="user",
        content="候选人简历：张三，计算机科学本科，5年后端开发经验，精通python和数据库设计。",
        parent_id= system_prompt.id
    )

    subtask_parse.add_prompt(resume_prompt)

    Task.preserve_semantics(chain=subtask_parse.context_chain,current_prompt=resume_prompt)
